package com.Thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName Demo6
 * @Description 编写程序，使用多线程，实现电影院售票的过程。
 * 多个线程共同卖相同的50张票 -- 实现 Runnable Callable
 * @Author Kx
 * @Date 2025/3/11 13:53
 * @Version 1.0
 */
public class Demo6 {
    public static void main(String[] args) {
//        MyThread4 myThread4 = new MyThread4();
//
//        Thread thread1 = new Thread(myThread4);
//        Thread thread2 = new Thread(myThread4);
//        Thread thread3 = new Thread(myThread4);
//
//        // 设置线程名
//        thread1.setName("线程一");
//        thread2.setName("线程二");
//        thread3.setName("线程三");
//
//        // 启动线程
//        thread1.start();
//        thread2.start();
//        thread3.start();


        MyThread5 myThread5 = new MyThread5();
        // 创建线程池(一共三条线程池)
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        // 提交任务给线程池
        executorService.submit(myThread5);
        executorService.submit(myThread5);
        executorService.submit(myThread5);

        // 关闭线程池
        executorService.shutdown();
    }
}

//class MyThread4 implements Runnable {
//    private int ticket = 50;
//
//    public int getTicket() {
//        return ticket;
//    }
//
//    public void setTicket(int ticket) {
//        this.ticket = ticket;
//    }
//
//
//    @Override
//    public synchronized void run() {
//        while (ticket > 0){
//            System.out.println(Thread.currentThread().getName() + "卖出了第" + ticket-- + "张票");
//        }
//    }
//}


class MyThread5 implements Callable {
    private AtomicInteger ticket = new AtomicInteger(50);
    @Override
    public Object call() throws Exception {
        while (ticket.get() > 0){
            // 获取票数并递减
            int andDecrement = ticket.getAndDecrement();
            if(andDecrement > 0){
                System.out.println(Thread.currentThread().getName() + "卖出了第" + andDecrement + "张票");
            }
        }
        return ticket;
    }
}


